package com.example.readandwriteseparation.aspect;

import com.example.readandwriteseparation.anno.Db;
import com.example.readandwriteseparation.config.DataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * db-asoect
 *
 * @author qingyan 2021-09-02
 */
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.example.readandwriteseparation.anno.Db)")
    public void daoAspect() {
    }


    @Before("daoAspect()&&@annotation(anno)")
    public void switchDataSource(JoinPoint point, Db anno) {

        String value = anno.value();
        String dataSourceKey = DataSourceHolder.getDataSourceKey();
        log.info("方法[{}]当前的数据源：{}", point.getSignature(), dataSourceKey);
        if (value.equals(dataSourceKey)) {
            return;
        }
        DataSourceHolder.setDataSourceKey(value);
        log.info("方法[{}]切换的数据源：{}", point.getSignature(), value);
    }


    @After("daoAspect()&&@annotation(anno)")
    public void restoreDataSource(JoinPoint point, Db anno) {
        DataSourceHolder.clearDataSourceKey();
        log.info("方法[{}]恢复原数据源", point.getSignature());
    }

}
